宣告會提升但賦值不會


test()

const test = function() {
  console.log('test')
}
// Uncaught ReferenceError: Cannot access 'test' before initialization

在 function 裡的 a 提升

宣告變數會提升,賦值不會

var a = 'global'

function test() {
  console.log(a)
  var a = '10'
}

test()
// a is undelined

function 的優先度高於宣告變數

function test() {
  console.log(a)
  function a() {}
  var a = 'local'
}

test() // f a() {}

同時宣告兩個一樣的 function,後者勝

var a = 'global'

function test() {
  a()
  function a() {
    console.log(1)
  }
  function a() {
    console.log(2)
  }
  var a = 'local'
}

test() // 2

hoisting 提升的順序

  1. function
  2. arguments (參數)
  3. var

參考資源


#程式導師實驗計畫第四期 #前端 #hoisting







Related Posts

一起來看 Joshua B. Tenenbaum 教授有趣的認知科學研究 - Building Machines that Learn and Think Like People

一起來看 Joshua B. Tenenbaum 教授有趣的認知科學研究 - Building Machines that Learn and Think Like People

Letter Combinations of a Phone Number

Letter Combinations of a Phone Number

[第十一週] 加密與雜湊 hash

[第十一週] 加密與雜湊 hash


Comments